package com.xohm.cm.gui.table;

import java.awt.event.MouseAdapter;
import java.awt.event.*;
import javax.swing.table.*;

public class HeaderListener extends MouseAdapter
{
	JTableHeader header;

	SortButtonRenderer renderer;

	public HeaderListener(JTableHeader header, SortButtonRenderer renderer)
	{
		this.header = header;
		this.renderer = renderer;
	}

	public void mousePressed(MouseEvent e)
	{
		int col = header.columnAtPoint(e.getPoint());
		int sortCol = header.getTable().convertColumnIndexToModel(col);
		renderer.setPressedColumn(col);
		renderer.setSelectedColumn(col);
		header.repaint();

		if (header.getTable().isEditing())
		{
			header.getTable().getCellEditor().stopCellEditing();
		}

		boolean isAscent;
		if (SortButtonRenderer.DOWN == renderer.getState(col))
		{
			isAscent = true;
		}
		else
		{
			isAscent = false;
		}
		header.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
		((SortableTableModel) header.getTable().getModel()).sortByColumn(sortCol, isAscent);
		header.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
	}

	public void mouseReleased(MouseEvent e)
	{
		header.columnAtPoint(e.getPoint());
		renderer.setPressedColumn(-1); // clear
		header.repaint();
	}
}
